<template>
  <view class="empty-pallet-container">
    <!-- 功能选择标签页 -->
    <view class="tab-section">
      <view class="tab-list">
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === 'return' }"
          @click="switchTab('return')"
        >
          <text class="tab-text">空拖回库</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === 'call' }"
          @click="switchTab('call')"
        >
          <text class="tab-text">呼叫空拖</text>
        </view>
      </view>
    </view>

    <!-- 空拖回库表单 -->
    <view class="form-section" v-if="activeTab === 'return'">
      <view class="form-header">
        <text class="form-title">空拖回库</text>
        <text class="form-desc">将空拖盘从指定起点回库</text>
      </view>

      <view class="form-item">
        <text class="label">起点
          <text class="required">*</text>
        </text>
        <input
          v-model="returnForm.startLocation"
          class="input"
          type="text"
          placeholder="请扫描或输入起点位置"
          @focus="currentFocusField = 'returnStartLocation'"
        />
      </view>

      <view class="form-item">
        <text class="label">拖盘规格
          <text class="required">*</text>
        </text>
        <picker 
          mode="selector" 
          :range="emptyPalletList" 
          range-key="type" 
          @change="onReturnPalletChange" 
          :value="returnPalletIndex"
          class="picker-wrapper"
        >
          <view class="input picker-input">
            {{ returnPalletIndex >= 0 ? emptyPalletList[returnPalletIndex].type : '请选择拖盘规格' }}
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

<!--      <view class="form-item">
        <text class="label">托盘号
          <text class="required">*</text>
        </text>
        <input
          v-model="returnForm.palletNumber"
          class="input"
          type="text"
          placeholder="请扫描或输入托盘号"
          @focus="currentFocusField = 'returnPalletNumber'"
        />
      </view>-->


      <view class="btn-group">
        <button @click="handleReturnReset" class="btn btn-default">重置</button>
        <button @click="handleReturnSubmit" class="btn btn-primary" :disabled="returnLoading">
          <text v-if="returnLoading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ returnLoading ? '提交中...' : '空拖回库' }}
        </button>
      </view>
    </view>

    <!-- 呼叫空拖表单 -->
    <view class="form-section" v-if="activeTab === 'call'">
      <view class="form-header">
        <text class="form-title">呼叫空拖</text>
        <text class="form-desc">呼叫空拖盘到指定终点</text>
      </view>

      <view class="form-item">
        <text class="label">拖盘规格
          <text class="required">*</text>
        </text>
        <picker 
          mode="selector" 
          :range="emptyPalletList" 
          range-key="type" 
          @change="onCallPalletChange" 
          :value="callPalletIndex"
          class="picker-wrapper"
        >
          <view class="input picker-input">
            {{ callPalletIndex >= 0 ? emptyPalletList[callPalletIndex].type : '请选择拖盘规格' }}
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">终点
          <text class="required">*</text>
        </text>
        <input
          v-model="callForm.endLocation"
          class="input"
          type="text"
          placeholder="请扫描或输入终点位置"
          @focus="currentFocusField = 'callEndLocation'"
        />
      </view>

      <view class="form-item">
        <text class="label">备注</text>
        <input
          v-model="callForm.remark"
          class="input"
          type="text"
          placeholder="请输入备注信息（可选）"
          @focus="currentFocusField = 'callRemark'"
        />
      </view>

      <view class="btn-group">
        <button @click="handleCallReset" class="btn btn-default">重置</button>
        <button @click="handleCallSubmit" class="btn btn-primary" :disabled="callLoading">
          <text v-if="callLoading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ callLoading ? '提交中...' : '呼叫空拖' }}
        </button>
      </view>
    </view>

    <!-- 扫码提示 -->
    <view class="scan-tip">
      <text class="tip-text">💡 支持扫码输入，点击输入框后扫码，内容将自动填入当前选中的字段</text>
    </view>
  </view>
</template>

<script>
import { emptyPalletReturn, emptyPalletCall, listAllPallets } from '@/api/system/emptyPallet';

var main, receiver, filter;

export default {
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'return',
      
      // 当前获得焦点的字段
      currentFocusField: '',
      
      // 托盘列表数据
      emptyPalletList: [],
      returnPalletIndex: -1,
      callPalletIndex: -1,
      
      // 空拖回库表单数据
      returnForm: {
        startLocation: '',
        containerType: '',
        palletNumber: '',
        remark: ''
      },
      
      // 呼叫空拖表单数据
      callForm: {
        containerType: '',
        endLocation: '',
        remark: ''
      },
      
      // 加载状态
      returnLoading: false,
      callLoading: false
    };
  },

  onLoad() {
    this.initScan();
    this.loadPalletList();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
    // 切换标签页
    switchTab(tab) {
      this.activeTab = tab;
    },

    // 加载托盘列表
    async loadPalletList() {
      try {
        const response = await listAllPallets();
        if (response.code === 200 && response.data) {
          // 过滤出空拖盘类型（palletType为"2"）
          this.emptyPalletList = response.data.filter(item => item.palletType === "2");
          console.log('空拖盘列表:', this.emptyPalletList);
        }
      } catch (error) {
        console.error('获取托盘列表失败:', error);
        this.$modal.msgError('获取托盘列表失败');
      }
    },

    // 空拖回库托盘选择变化
    onReturnPalletChange(e) {
      this.returnPalletIndex = e.detail.value;
      const selectedPallet = this.emptyPalletList[this.returnPalletIndex];
      if (selectedPallet) {
        this.returnForm.containerType = selectedPallet.type;
        console.log('选择的拖盘规格:', selectedPallet);
      }
    },

    // 呼叫空拖托盘选择变化
    onCallPalletChange(e) {
      this.callPalletIndex = e.detail.value;
      const selectedPallet = this.emptyPalletList[this.callPalletIndex];
      if (selectedPallet) {
        this.callForm.containerType = selectedPallet.type;
        console.log('选择的拖盘规格:', selectedPallet);
      }
    },

    // 初始化扫码功能
    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          console.log('扫码结果:', code);
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    // 开始扫码监听
    startScan() {
      /* #ifdef APP-PLUS */
      if (main && receiver && filter) {
        main.registerReceiver(receiver, filter);
      }
      /* #endif */
    },

    // 停止扫码监听
    stopScan() {
      /* #ifdef APP-PLUS */
      if (main && receiver) {
        main.unregisterReceiver(receiver);
      }
      /* #endif */
    },

    // 处理扫码结果
    handleScanResult(code) {
      // 清理扫码内容，去除可能的前缀
      let cleanCode = code;
      if (code.startsWith('L') || code.startsWith('P') || code.startsWith('M')) {
        cleanCode = code.substring(1);
      }
      
      // 根据当前获得焦点的字段填入扫码结果
      switch (this.currentFocusField) {
        case 'returnStartLocation':
          this.returnForm.startLocation = cleanCode;
          break;
        case 'returnPalletNumber':
          this.returnForm.palletNumber = cleanCode;
          break;
        case 'returnRemark':
          this.returnForm.remark = cleanCode;
          break;
        case 'callEndLocation':
          this.callForm.endLocation = cleanCode;
          break;
        case 'callRemark':
          this.callForm.remark = cleanCode;
          break;
        default:
          // 如果没有焦点字段，根据当前标签页和字段是否为空来智能填入
          if (this.activeTab === 'return') {
            if (!this.returnForm.startLocation) {
              this.returnForm.startLocation = cleanCode;
            } else if (!this.returnForm.palletNumber) {
              this.returnForm.palletNumber = cleanCode;
            }
          } else if (this.activeTab === 'call') {
            if (!this.callForm.endLocation) {
              this.callForm.endLocation = cleanCode;
            }
          }
          break;
      }
    },

    // 重置空拖回库表单
    handleReturnReset() {
      this.returnForm = {
        startLocation: '',
        containerType: '',
        palletNumber: '',
        remark: ''
      };
      this.returnPalletIndex = -1;
    },

    // 重置呼叫空拖表单
    handleCallReset() {
      this.callForm = {
        containerType: '',
        endLocation: '',
        remark: ''
      };
      this.callPalletIndex = -1;
    },

    // 提交空拖回库
    async handleReturnSubmit() {
      if (this.returnLoading) return;

      // 表单验证
      if (!this.returnForm.startLocation) {
        this.$modal.msgError('请输入起点位置');
        return;
      }
      if (!this.returnForm.containerType) {
        this.$modal.msgError('请选择拖盘规格');
        return;
      }
      /*if (!this.returnForm.palletNumber) {
        this.$modal.msgError('请输入托盘号');
        return;
      }*/

      this.returnLoading = true;
      this.$modal.loading('空拖回库中，请稍候...');

      try {
        const response = await emptyPalletReturn({
          startLocation: this.returnForm.startLocation,
          containerType: this.returnForm.containerType,
          palletNumber: this.returnForm.palletNumber,
          remark: this.returnForm.remark
        });

        this.$modal.closeLoading();
        
        if (response.code === 200) {
          this.$modal.msgSuccess('空拖回库任务创建成功');
          this.handleReturnReset();
        } else {
          this.$modal.msgError(response.msg || '空拖回库失败');
        }
      } catch (error) {
        this.$modal.closeLoading();
        console.error('空拖回库错误:', error);
        this.$modal.msgError('空拖回库失败，请重试');
      } finally {
        this.returnLoading = false;
      }
    },

    // 提交呼叫空拖
    async handleCallSubmit() {
      if (this.callLoading) return;

      // 表单验证
      if (!this.callForm.containerType) {
        this.$modal.msgError('请选择拖盘规格');
        return;
      }
      if (!this.callForm.endLocation) {
        this.$modal.msgError('请输入终点位置');
        return;
      }

      this.callLoading = true;
      this.$modal.loading('呼叫空拖中，请稍候...');

      try {
        const response = await emptyPalletCall({
          containerType: this.callForm.containerType,
          endLocation: this.callForm.endLocation,
          remark: this.callForm.remark
        });

        this.$modal.closeLoading();
        
        if (response.code === 200) {
          this.$modal.msgSuccess('空拖呼叫任务创建成功');
          this.handleCallReset();
        } else {
          this.$modal.msgError(response.msg || '空拖呼叫失败');
        }
      } catch (error) {
        this.$modal.closeLoading();
        console.error('空拖呼叫错误:', error);
        this.$modal.msgError('空拖呼叫失败，请重试');
      } finally {
        this.callLoading = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
}

.empty-pallet-container {
  min-height: 100vh;
  padding: 0;
}

/* 标签页样式 */
.tab-section {
  background: #fff;
  border-bottom: 1px solid #e5e5e5;
}

.tab-list {
  display: flex;
  padding: 0 16px;
}

.tab-item {
  flex: 1;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  &.active {
    .tab-text {
      color: #4A90E2;
      font-weight: 600;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 24px;
      height: 2px;
      background: #4A90E2;
      border-radius: 1px;
    }
  }
}

.tab-text {
  font-size: 16px;
  color: #666;
  transition: all 0.3s ease;
}

/* 表单样式 */
.form-section {
  background: #fff;
  margin: 12px 16px;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-header {
  margin-bottom: 20px;
  
  .form-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 4px;
  }
  
  .form-desc {
    font-size: 14px;
    color: #999;
  }
}

.form-item {
  margin-bottom: 16px;
  
  .label {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
  }
  
  .required {
    color: #ff4757;
    margin-left: 2px;
  }
  
  .input {
    width: 100%;
    height: 44px;
    padding: 0 12px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    font-size: 16px;
    color: #333;
    
    &:focus {
      border-color: #4A90E2;
      background: #fff;
    }
  }
}

/* 按钮样式 */
.btn-group {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.btn {
  flex: 1;
  height: 44px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  
  &.btn-default {
    background: #f8f9fa;
    color: #666;
    
    &:active {
      background: #e9ecef;
    }
  }
  
  &.btn-primary {
    background: #4A90E2;
    color: #fff;
    
    &:active {
      background: #357abd;
    }
    
    &:disabled {
      background: #b0b0b0;
      color: #fff;
    }
  }
}

/* 扫码提示 */
.scan-tip {
  margin: 20px 16px;
  padding: 12px 16px;
  background: #e8f4fd;
  border-radius: 6px;
  border-left: 3px solid #4A90E2;
  
  .tip-text {
    font-size: 13px;
    color: #4A90E2;
    line-height: 1.4;
  }
}

/* 选择器样式 */
.picker-wrapper {
  width: 100%;
}

.picker-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.picker-arrow {
  color: #999;
  font-size: 12px;
  margin-left: 12px;
}

/* 加载动画 */
.iconfont-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 